package com.example.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import com.example.tests.SortedListOf;
import com.example.tests.User;

public class UserManagementPage extends InternalPage {

	@FindBy(xpath = "html/body/div[1]/div/div/section/div[1]/h2")
	public WebElement title;

	@FindBy(xpath = "//tr[1]/td[2]/input")
	public WebElement userNameField;

	@FindBy(xpath = "//tr[2]/td[2]/input")
	public WebElement userEmail;

	@FindBy(xpath = "//tr[3]/td[2]/input")
	public WebElement userPassword1;

	@FindBy(xpath = "//tr[4]/td[2]/input")
	public WebElement userPassword2;

	@FindBy(xpath = "//tr[6]/td[2]/input")
	public WebElement saveButton;

	@FindBy(css = "div#user-list table > tbody > tr")
	public List<WebElement> userRows;

	public boolean isUserManagementOpened() {
		return title.isDisplayed();
	}

	public UserManagementPage createNewUser(User user) {
		userNameField.sendKeys(user.name);
		userEmail.sendKeys(user.email);
		userPassword1.sendKeys(user.password);
		userPassword2.sendKeys(user.password);
		saveButton.click();
		cachedUsers = null;
		return MyPageFactory.getPage(driver, UserManagementPage.class);
	}

	public UserManagementPage deleteUser(User user) {
		for (WebElement row : userRows) {
			if (user.equals(convertRowToUser(row))) {
				row.findElement(By.xpath("./td[6]/a")).click();
				waiter().until(alertIsPresent()).accept();
				break;
			}
		}
		cachedUsers = null;
		return MyPageFactory.getPage(driver, UserManagementPage.class);
	}

	private SortedListOf<User> cachedUsers;

	public SortedListOf<User> getUsers() {
		if (cachedUsers == null) {
			cachedUsers = new SortedListOf<User>();
			for (WebElement row : userRows) {
				cachedUsers.add(convertRowToUser(row));
			}
		}
		return new SortedListOf<User>(cachedUsers);
	}

	private User convertRowToUser(WebElement row) {
		List<WebElement> cells = row.findElements(By.tagName("td"));
		return new User().withName(cells.get(1).getText()).withEmail(
				cells.get(2).getText());
	}

}
